package jdbc;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;

import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;

import modelo.Cliente;
import dao.ClienteDAO;

public class JdbcClienteDAO implements ClienteDAO{

	private Connection connection;
	
	
	public JdbcClienteDAO(Connection connection){
		this.connection = connection;
	}
	
	public void inserir(Cliente cliente) {
		
		String sql = "insert into cliente(cpf,nome,endereco,cidade,estado,sexo,tema) values ( ?,?,?,?,?,?,?)";
		PreparedStatement stmt;
		try {
			stmt = (PreparedStatement) this.connection.prepareStatement(sql);
			stmt.setString(1, cliente.getCpf());
			stmt.setString(2, cliente.getNome());
			stmt.setString(3, cliente.getEndereco());
			stmt.setString(4, cliente.getCidade());
			stmt.setString(5, cliente.getEstado());
			stmt.setObject(6, cliente.getSexo());
			stmt.setString(7, cliente.getTemaInteresse());
			
			stmt.execute();
		
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		
		
		
	}
	
	public ArrayList<Cliente> listaClientes(){
		
		ArrayList<Cliente> todosClientes = new ArrayList<Cliente>();
		
		String sql = "select codigo,nome,cpf from cliente";
		try {
			PreparedStatement stmt = (PreparedStatement) this.connection.prepareStatement(sql);
			ResultSet rs = (ResultSet) stmt.executeQuery();
			
			while(rs.next()){
				Cliente cliente = new Cliente();
				cliente.setCodigo(rs.getInt("codigo"));
				cliente.setNome(rs.getString("nome"));
				cliente.setCpf(rs.getString("cpf"));
				todosClientes.add(cliente);
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return todosClientes;
	}
	
	public Cliente buscaCliente(int codigo){
		
		String sql = "select * from cliente where codigo = ?";
		Cliente cliente = new Cliente();
		
		try {
			PreparedStatement stmt = (PreparedStatement) this.connection.prepareStatement(sql);
		    stmt.setInt(1,codigo);
		    ResultSet rs = (ResultSet) stmt.executeQuery();
		    rs.next();
		    
		    cliente.setCpf(rs.getString("cpf"));
		    cliente.setNome(rs.getString("nome"));
		    cliente.setCidade(rs.getString("cidade"));
		    cliente.setEndereco(rs.getString("endereco"));
		    cliente.setEstado(rs.getString("estado"));
		    
		    
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return cliente;
		
	}

	
	
}
